{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a8b892c8",
   "metadata": {},
   "source": [
    "Printed and electronic copies of *Modeling and Simulation in Python* are available from [No Starch Press](https://nostarch.com/modeling-and-simulation-python) and [Bookshop.org](https://bookshop.org/p/books/modeling-and-simulation-in-python-allen-b-downey/17836697?ean=9781718502161) and [Amazon](https://amzn.to/3y9UxNb)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "medieval-johnston",
   "metadata": {},
   "source": [
    "# Adding Milk"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fifty-chicken",
   "metadata": {
    "tags": []
   },
   "source": [
    "*Modeling and Simulation in Python*\n",
    "\n",
    "Copyright 2021 Allen Downey\n",
    "\n",
    "License: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "british-place",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# download modsim.py if necessary\n",
    "\n",
    "from os.path import basename, exists\n",
    "\n",
    "def download(url):\n",
    "    filename = basename(url)\n",
    "    if not exists(filename):\n",
    "        from urllib.request import urlretrieve\n",
    "        local, _ = urlretrieve(url, filename)\n",
    "        print('Downloaded ' + local)\n",
    "    \n",
    "download('https://github.com/AllenDowney/ModSimPy/raw/master/' +\n",
    "         'modsim.py')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "determined-volunteer",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# import functions from modsim\n",
    "\n",
    "from modsim import *"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "valuable-shannon",
   "metadata": {
    "tags": []
   },
   "source": [
    "This chapter is available as a Jupyter notebook where you can read the text, run the code, and work on the exercises. \n",
    "Click here to access the notebooks: <https://allendowney.github.io/ModSimPy/>."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "fossil-moisture",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "download('https://github.com/AllenDowney/ModSimPy/raw/master/' +\n",
    "         'chap15.py')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "cutting-scale",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# import code from previous notebooks\n",
    "\n",
    "from chap15 import change_func\n",
    "from chap15 import run_simulation\n",
    "from chap15 import make_system"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "enhanced-copper",
   "metadata": {},
   "source": [
    "In the previous chapter we wrote a simulation of a cooling cup of\n",
    "coffee. \n",
    "Given the initial temperature of the coffee, the temperature of the atmosphere, and the rate parameter, `r`, we predicted the temperature of the coffee over time.\n",
    "Then we used a root finding algorithm to estimate `r` based on data.\n",
    "\n",
    "If you did the exercises, you simulated the temperature of the milk as it warmed, and estimated its rate parameter as well.\n",
    "\n",
    "Now let's put it together.\n",
    "In this chapter we'll write a function that simulates mixing the two liquids, and use it to answer the question we started with: is it better to mix the coffee and milk at the beginning, the end, or somewhere in the middle?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hydraulic-belfast",
   "metadata": {},
   "source": [
    "## Mixing Liquids\n",
    "\n",
    "When we mix two liquids, the temperature of the mixture depends on the\n",
    "temperatures of the ingredients as well as their volumes, densities, and specific heat capacities (as defined in the previous chapter).\n",
    "In this section I'll explain how.\n",
    "\n",
    "Assuming there are no chemical reactions that either produce or consume heat, the total thermal energy of the system is the same before and after mixing; in other words, thermal energy is *conserved*.\n",
    "\n",
    "If the temperature of the first liquid is $T_1$, the temperature of the second liquid is $T_2$, and the final temperature of the mixture is $T$, the heat transfer into the first liquid is $C_1 (T - T_1)$ and the heat transfer into the second liquid is $C_2 (T - T_2)$, where $C_1$ and $C_2$ are the thermal masses of the liquids.\n",
    "\n",
    "In order to conserve energy, these heat transfers must add up to 0:\n",
    "\n",
    "$$C_1 (T - T_1) + C_2 (T - T_2) = 0$$ \n",
    "\n",
    "We can solve this equation for T:\n",
    "\n",
    "$$T = \\frac{C_1 T_1 + C_2 T_2}{C_1 + C_2}$$ \n",
    "\n",
    "For the coffee cooling problem, we have the volume of each liquid; if we also know the density, $\\rho$, and the specific heat capacity, $c_p$, we can compute thermal mass: \n",
    "\n",
    "$$C = \\rho V c_p$$ \n",
    "\n",
    "If the liquids have the same density and heat capacity, they drop out of the equation, and we can write:\n",
    "\n",
    "$$T = \\frac{V_1 T_1 + V_2 T_2}{V_1 + V_2}$$ \n",
    "\n",
    "where $V_1$ and $V_2$ are the volumes of the liquids.\n",
    "\n",
    "As an approximation, I'll assume that milk and coffee have the same\n",
    "density and specific heat. If you are interested, you can look up these\n",
    "quantities and see how good this assumption is.\n",
    "\n",
    "Now let's simulate the mixing process.\n",
    "The following function takes two `System` objects, representing the\n",
    "coffee and milk, and creates a new `System` to represent the mixture:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "extensive-happening",
   "metadata": {},
   "outputs": [],
   "source": [
    "def mix(system1, system2):\n",
    "    \n",
    "    V1, V2 = system1.volume, system2.volume\n",
    "    T1, T2 = system1.T_final, system2.T_final\n",
    "    \n",
    "    V_mix = V1 + V2\n",
    "    T_mix = (V1 * T1 + V2 * T2) / V_mix\n",
    "    \n",
    "    return make_system(T_init=T_mix,\n",
    "                       volume=V_mix,\n",
    "                       r=system1.r,\n",
    "                       t_end=30)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "overhead-architect",
   "metadata": {},
   "source": [
    "The first two lines extract volume and temperature from the `System` objects. The next two lines compute the volume and temperature of the mixture. Finally, `mix` makes a new `System` object and returns it.\n",
    "\n",
    "This function uses the value of `r` from `system1` as the value of `r`\n",
    "for the mixture. If `system1` represents the coffee, and we are adding\n",
    "the milk to the coffee, this is probably a reasonable choice. On the\n",
    "other hand, when we increase the amount of liquid in the coffee cup,\n",
    "that might change `r`. So this is an assumption we might want to\n",
    "revisit.\n",
    "\n",
    "Now we have everything we need to solve the problem."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "foreign-campbell",
   "metadata": {},
   "source": [
    "## Mix First or Last?\n",
    "\n",
    "First I'll create objects to represent the coffee and milk.\n",
    "For `r_coffee`, I'll use the value we computed in the previous chapter."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "polyphonic-specialist",
   "metadata": {},
   "outputs": [],
   "source": [
    "r_coffee = 0.0115\n",
    "coffee = make_system(T_init=90, volume=300, r=r_coffee, t_end=30)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "authorized-system",
   "metadata": {},
   "source": [
    "For `r_milk`, I'll use the value I estimated in the exercise from the previous chapter."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "subtle-donna",
   "metadata": {},
   "outputs": [],
   "source": [
    "r_milk = 0.133\n",
    "milk = make_system(T_init=5, volume=50, r=r_milk, t_end=15)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "satisfactory-rwanda",
   "metadata": {},
   "source": [
    "Now we can mix them and simulate 30 minutes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "domestic-tours",
   "metadata": {},
   "outputs": [],
   "source": [
    "mix_first = mix(coffee, milk)\n",
    "run_simulation(mix_first, change_func)\n",
    "\n",
    "mix_first.T_final"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "accredited-diagnosis",
   "metadata": {},
   "source": [
    "The final temperature is 61.5 °C which is still warm enough to be\n",
    "enjoyable. Would we do any better if we added the milk last?\n",
    "\n",
    "I'll simulate the coffee and milk separately, and then mix them:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "subject-richardson",
   "metadata": {},
   "outputs": [],
   "source": [
    "run_simulation(coffee, change_func)\n",
    "run_simulation(milk, change_func)\n",
    "mix_last = mix(coffee, milk)\n",
    "mix_last.T_final"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "divine-trance",
   "metadata": {},
   "source": [
    "After mixing, the temperature is 62.9 °C, so it looks like adding the\n",
    "milk at the end is better. \n",
    "But is that the best we can do?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "linear-republican",
   "metadata": {},
   "source": [
    "## Optimal Timing\n",
    "\n",
    "Adding the milk after 30 minutes is better than adding it immediately, but maybe there's something in between that's even better. To find out, I'll use the following function, which takes the time to add the milk, `t_add`, as a parameter:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "mental-corporation",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_and_mix(t_add, t_total):\n",
    "    coffee.t_end = t_add\n",
    "    coffee_results = run_simulation(coffee, change_func)\n",
    "    \n",
    "    milk.t_end = t_add\n",
    "    milk_results = run_simulation(milk, change_func)\n",
    "    \n",
    "    mixture = mix(coffee, milk)\n",
    "    mixture.t_end = t_total - t_add\n",
    "    results = run_simulation(mixture, change_func)\n",
    "\n",
    "    return mixture.T_final"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "better-cemetery",
   "metadata": {},
   "source": [
    "`run_and_mix` simulates both systems for the given time, `t_add`.\n",
    "Then it mixes them and simulates the mixture for the remaining time, `t_total - t_add`.\n",
    "\n",
    "When `t_add` is `0`, we add the milk immediately; when `t_add` is `30`, we add it at the end. Now we can sweep the range of values in between:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "adverse-hanging",
   "metadata": {},
   "outputs": [],
   "source": [
    "sweep = SweepSeries()\n",
    "for t_add in linspace(0, 30, 11):\n",
    "    sweep[t_add] = run_and_mix(t_add, 30)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "practical-state",
   "metadata": {},
   "source": [
    "Here's what the results look like:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "bright-proposal",
   "metadata": {},
   "outputs": [],
   "source": [
    "sweep.plot(label='mixture', color='C2')\n",
    "\n",
    "decorate(xlabel='Time until mixing (min)',\n",
    "         ylabel='Final temperature (C)')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "experienced-tribute",
   "metadata": {},
   "source": [
    "Note that this is a parameter sweep, not a time series.\n",
    "\n",
    "The final temperature is maximized when `t_add=30`, so adding the milk\n",
    "at the end is optimal."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "rough-investor",
   "metadata": {},
   "source": [
    "## Analytic Solution\n",
    "\n",
    "Simulating Newton's law of cooling isn't really necessary because we can solve the differential equation analytically. If\n",
    "\n",
    "$$\\frac{dT}{dt} = -r (T - T_{env})$$ \n",
    "\n",
    "the general solution is\n",
    "\n",
    "$$T{\\left (t \\right )} = C \\exp(-r t) + T_{env}$$ \n",
    "\n",
    "and the particular solution where $T(0) = T_{init}$ is\n",
    "\n",
    "$$T_{env} + \\left(- T_{env} + T_{init}\\right) \\exp(-r t)$$ \n",
    "\n",
    "If you would like to see this solution done by hand, you can watch this video: <http://modsimpy.com/khan3>."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "chief-abortion",
   "metadata": {},
   "source": [
    "Now we can use the observed data to estimate the parameter $r$. If we\n",
    "observe the that the temperature at $t_{end}$ is $T_{final}$, we can plug these values into the particular solution and solve for $r$. The result is:\n",
    "\n",
    "$$r = \\frac{1}{t_{end}} \\log{\\left (\\frac{T_{init} - T_{env}}{T_{final} - T_{env}} \\right )}$$\n",
    "\n",
    "The following function takes a `System` object and computes `r`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "secondary-swift",
   "metadata": {},
   "outputs": [],
   "source": [
    "from numpy import log\n",
    "\n",
    "def compute_r(system):\n",
    "    t_end = system.t_end\n",
    "    T_init = system.T_init\n",
    "    T_final = system.T_final\n",
    "    T_env = system.T_env\n",
    "    \n",
    "    r = log((T_init - T_env) / (T_final - T_env)) / t_end\n",
    "    return r"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "correct-spare",
   "metadata": {},
   "source": [
    "We can use this function to compute `r` for the coffee, given the parameters of the problem."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "south-machinery",
   "metadata": {},
   "outputs": [],
   "source": [
    "coffee2 = make_system(T_init=90, volume=300, r=0, t_end=30)\n",
    "coffee2.T_final = 70\n",
    "r_coffee2 = compute_r(coffee2)\n",
    "r_coffee2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "worthy-steal",
   "metadata": {},
   "source": [
    "This value is close to the value of `r` we computed in the previous chapter, `0.115`, but not exactly the same.\n",
    "That's because the simulations use discrete time steps, and the analysis uses continuous time.\n",
    "\n",
    "Nevertheless, the results of the analysis are consistent with the simulation.\n",
    "To check, we'll use the following function, which takes a `System` object and uses the analytic result to compute a time series:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "opening-transsexual",
   "metadata": {},
   "outputs": [],
   "source": [
    "from numpy import exp\n",
    "\n",
    "def run_analysis(system):\n",
    "    T_env, T_init, r = system.T_env, system.T_init, system.r\n",
    "    \n",
    "    t_array = linrange(system.t_0, system.t_end, system.dt)    \n",
    "    T_array = T_env + (T_init - T_env) * exp(-r * t_array)\n",
    "    \n",
    "    system.T_final = T_array[-1]\n",
    "    return make_series(t_array, T_array)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fallen-spiritual",
   "metadata": {},
   "source": [
    "The first line unpacks the system variables.\n",
    "The next two lines compute `t_array`, which is a NumPy array of time stamps, and `T_array`, which is an array of the corresponding temperatures.\n",
    "The last two lines store the final temperature in the `System` object and use `make_series` to return the results in a Pandas `Series`.\n",
    "\n",
    "We can run it like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "agreed-bouquet",
   "metadata": {},
   "outputs": [],
   "source": [
    "coffee2.r = r_coffee2\n",
    "results2 = run_analysis(coffee2)\n",
    "coffee2.T_final"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "exact-juice",
   "metadata": {},
   "source": [
    "The final temperature is 70 °C, as it should be. In fact, the results\n",
    "are identical to what we got by simulation, with a small difference due to rounding."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "portuguese-sympathy",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "coffee.r = 0.011543\n",
    "results = run_simulation(coffee, change_func)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "distinguished-regard",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from numpy import allclose\n",
    "\n",
    "allclose(results, results2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "floral-homework",
   "metadata": {},
   "source": [
    "Since we can solve this problem analytically, you might wonder why we bothered writing a simulation. \n",
    "One reason is validation: since we solved the same problem two ways, we can be more confident that the answer is correct. \n",
    "The other reason is flexibility: now that we have a working simulation, it would be easy to add more features. For example, the temperature of the environment might change over time, or we could simulate the coffee and container as two objects. \n",
    "If the coffee and milk are next to each other, we could include the heat flow between them. A model with these features would be difficult or impossible to solve analytically. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "rapid-payroll",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "In this chapter we finished the coffee cooling problem from the previous chapter, and found that it is better to add the milk at the end, at least for the version of the problem I posed.\n",
    "\n",
    "As an exercise you will have a chance to explore a variation of the problem where the answer might be different.\n",
    "\n",
    "In the next chapter we'll move on to a new example, a model of how glucose and insulin interact to control blood sugar."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "gothic-clearance",
   "metadata": {},
   "source": [
    "## Exercises\n",
    "\n",
    "This chapter is available as a Jupyter notebook where you can read the text, run the code, and work on the exercises. \n",
    "You can access the notebooks at <https://allendowney.github.io/ModSimPy/>."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "foreign-permission",
   "metadata": {},
   "source": [
    "### Exercise 1\n",
    "\n",
    "Use `compute_r` to compute `r_milk` according to the analytic solution.  Run the analysis with this value of `r_milk` and confirm that the results are consistent with the simulation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "acting-howard",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "ahead-compensation",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "assumed-shock",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "elementary-moral",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "western-mixture",
   "metadata": {},
   "source": [
    "### Exercise 2\n",
    "\n",
    "Suppose the coffee shop won't let me take milk in a separate container, but I keep a bottle of milk in the refrigerator at my office.  In that case is it better to add the milk at the coffee shop, or wait until I get to the office?\n",
    "\n",
    "Hint: Think about the simplest way to represent the behavior of a refrigerator in this model.  The change you make to test this variation of the problem should be very small!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "super-citizenship",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
